<?php
  header("Cache-Control: no-cache, must-revalidate");
  header("Expires: Sun, 15 Mar 2009 05:00:00 GMT");
  include 'db-ubi.php';
  include 'functions-ubi.php';

  $sourceID = mysql_real_escape_string($postID);
  $factoidValue = mysql_real_escape_string(str_replace("%3F", "?",str_replace("%23", "#", $postFactoidValue)));
  $action = $postAction;

  if (isset($_SERVER["PHP_AUTH_USER"])) {
    $httpUsername = $_SERVER["PHP_AUTH_USER"]; // webform - $HTTP_USER
  }

  if ($action == "update" && $factoidValue != "" && $sourceID != "" && $sourceID > 0) {
    // The factoid value has to be updated, and both the key and the value was provided

    $sqlquery = sprintf("UPDATE `%s` SET `fact_value` = '%s', `editor_user_id` = %d, `date_last_changed` = CURRENT_TIMESTAMP WHERE `factoid_id` = %d",
                        $globalTableName, $factoidValue, 1, $sourceID);

    if (!mysql_query($sqlquery)) {
      // The update failed. We must retried the current value from the database
      $sqlquery = sprintf("SELECT `fact_value` FROM `%s` WHERE `factoid_id` = %d", $globalTableName, $sourceID);
      $queryresult = mysql_query($sqlquery);
      $row = mysql_fetch_array($queryresult);

      // Now make sure a value exists for this id
      if (mysql_num_rows($queryresult) > 0) {
        print "1:" . $row["fact_value"];
      } else {
        print "1:This factoid no longer exists.";
      }
    } else {
      // The update succeeded. Return the value specified by the user
      print "0:" . $postFactoidValue;
    }
  } else if ($action == "delete" && $sourceID != "") {
    $sqlquery = sprintf("UPDATE `%s` SET `is_visible` = 0, `editor_user_id` = %d, `date_last_changed` = CURRENT_TIMESTAMP WHERE `factoid_id` = %d",
                        $globalTableName, 1, $sourceID);

    if (!mysql_query($sqlquery)) {
      // The update failed. Tell the client it's still active (1: failed, 0: succeeded)
      print "1";
    } else {
      print "0";
    }
  } else if ($action == "activate" && $sourceID != "") {
    $sqlquery = sprintf("UPDATE `%s` SET `is_visible` = 1, `editor_user_id` = %d, `date_last_changed` = CURRENT_TIMESTAMP WHERE `factoid_id` = %d",
                        $globalTableName, 1, $sourceID);

    if (!mysql_query($sqlquery)) {
      // The update failed. Tell the client it's still deleted (1: failed, 0: succeeded)
      print "1";
    } else {
      print "0";
    }
  } else if ($action == "canceledit" && $sourceID != "") {
    $sqlquery = sprintf("SELECT `fact_value` FROM `%s` WHERE `factoid_id` = %d", $globalTableName, $sourceID);
    $queryresult = mysql_query($sqlquery);
    $row = mysql_fetch_array($queryresult);

    // Now make sure a value exists for this id
    if (mysql_num_rows($queryresult) > 0) {
      print "1:" . $row["fact_value"];
    } else {
      print "1:This factoid no longer exists.";
    }
  } else {
    print "";
  }
?>
